import { Layout } from '@cscec/udp-ui';
import { render } from 'amis';
import React, { CSSProperties, useRef } from 'react';
import commonArrowIcon from '@/assets/image/commonArrow.svg';
import styles from './index.less';

/**
 * 数据统计组
 */
export default function Statistic({ gap, list = [], height, style, env }: IProps) {
  const staticsRef = useRef<HTMLDivElement>(null);
  let averageWidth = 300;
  // 设置项的平均宽度
  if (list.length) {
    averageWidth = Math.floor(list.reduce((acc, cur) => acc + cur.width, 0) / list.length);
  }

  // 点击滚动
  const handleScroll = (direction: 'left' | 'right') => () => {
    if (staticsRef.current) {
      const { scrollLeft } = staticsRef.current;
      if (direction === 'left') {
        staticsRef.current.scrollTo(scrollLeft - averageWidth, 0);
      } else {
        staticsRef.current.scrollTo(scrollLeft + averageWidth, 0);
      }
    }
  };

  return (
    <div className={styles.statistics}>
      <img src={commonArrowIcon} alt="arrow-left" className={styles.arrowLeft} onClick={handleScroll('left')} />
      <Layout
        outRef={staticsRef}
        direction="row"
        style={{
          position: 'relative',
          height: height ?? (env.session === 'design' ? 150 : '100%'),
          overflow: 'auto',
          gap: gap ?? 'var(--outer-margin)',
          ...style
        }}
      >
        {render(
          list.map((c) => ({
            ...c,
            type: 'common-business-card'
          })) as any
        )}
      </Layout>
      <img src={commonArrowIcon} alt="arrow-right" className={styles.arrowRight} onClick={handleScroll('right')} />
    </div>
  );
}

export interface IProps {
  style?: CSSProperties;
  gap?: number;
  height?: number;
  list?: Array<{ width: number; src: string }>;
  [x: string]: any;
}
